/* 작성자 : Jint
 * 작성일 : 140423
 * 내용 : HashMap을 이용하여 데이터(회원)을 관리하기 위한 응용 예제 연습.
 * 		 HashMap 의 Key 값은 Data(Id, Name, Phone)의 ID값으로. (Key=ID)
 * 		 Value 값은 MapData 형식으로 저장.
 *		 HashMap<String, MapData> hm = new HashMap(); // ID 는 String 형식이므로 Key 자리에는 String.
 *		 
 *		 Main 창에서 Input, Update, List 를 InternalFrame 으로 제어할 것이기 때문에 Main 클래스에서 선언된 HashMap을 각각의 생성자에 매개변수로 넣어준다.
 *		 생성자를 넣어주고, 각각의 창이 생성될 때 Main 클래스의 HashMap을 전달받는다.  
 *
 */
package stream;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;

public class MapMain extends JFrame {
	String filename="Untitled";
	boolean modifyFlag = false;  // 수정여부, 종료시킬때 수정여부를 알아내서 저장할지 말지 묻기위한 변수.
	
	MapInput input = null;
	MapUpdate update = null;
	MapList list = null;
	HashMap<String, MapData> hm = new HashMap<String, MapData>();
	
	private JPanel contentPane;
	private JMenuBar menuBar;
	private JMenu mnFileProcess;
	private JMenuItem mntmInput;
	private JMenuItem mntmUpdate;
	private JMenuItem mntmList;
	private JMenu mnFile;
	private JMenuItem mntmNewFile;
	private JMenuItem mntmLoad;
	private JMenuItem mntmSave;
	private JMenuItem mntmSaveAs;
	private JLabel status;
	
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MapMain frame = new MapMain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public void newFile() throws Exception {
		if(modifyFlag){
			int yn = JOptionPane.showConfirmDialog(null, "변경된 내용이 있습니다. 저장 하시겠습니까?");
			if(yn == JOptionPane.YES_OPTION) save();
			status.setText("Your File is Safely Saved.");		
		}
		
		status.setText("New File Created.");		
		filename = "Untitled";
		setTitle("Filename : " + filename);
		
		
		Set <String> sk = hm.keySet();
		Iterator<String> it = sk.iterator();
		
		
		while(it.hasNext()){			
			hm.remove(it.next());		
		}
		
	}
	public void load() throws Exception{

		int yn=-1;
		
		if(modifyFlag){ // 현재 파일 내용이 수정된 경우
			yn = JOptionPane.showConfirmDialog(null, "파일이 수정되었습니다. 저장 하시겠습니까?");
			if(yn == JOptionPane.YES_OPTION) save();
		}
		
		// 저장된 이후이거나, 파일이 없거나...
		JFileChooser fc = new JFileChooser();
		yn = fc.showOpenDialog(this);		
		if(yn == JFileChooser.APPROVE_OPTION){ // 열기 버튼 클릭시
			File f = fc.getSelectedFile();
			
			filename = f.getPath();
			setTitle("Filename : " + filename);
			
			FileInputStream fis = new FileInputStream(filename);
			ObjectInputStream ois = new ObjectInputStream(fis);
			hm = (HashMap)ois.readObject();
			
			if(input != null) input.setMap(hm);
			if(update != null) update.setMap(hm);
			if(list != null) list.setMap(hm);
					
			ois.close();
			fis.close(); // 닫을때는 역순으로.
			
			
			
			status.setText("Your File Safely Loaded.");
		}
	}
	public void save() throws Exception{
		if(filename.equals("Untitled")){ // 파일명이 정해지지 않았을때
			saveAs();
		}
		
		FileOutputStream fos = new FileOutputStream(filename);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		oos.writeObject(hm);
		status.setText("Your File Safely Saved.");		
		oos.close();
		fos.close();
		setTitle("Filename : " + filename);
	}
	public void saveAs() throws Exception{
		JFileChooser fc = new JFileChooser(filename);
		int yn = fc.showSaveDialog(this);
		if(yn == JFileChooser.APPROVE_OPTION){
			File f = fc.getSelectedFile();
			filename = f.getPath();
			save();
		}	
	}
	
	

	public MapMain() {		
		setTitle("MapMain / Data Process");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1065, 572);
		setJMenuBar(getMenuBar_1());
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		contentPane.add(getStatus());
	}
	private JMenuBar getMenuBar_1() {
		if (menuBar == null) {
			menuBar = new JMenuBar();
			menuBar.add(getMnFile());
			menuBar.add(getMnFileProcess());
		}
		return menuBar;
	}
	private JMenu getMnFileProcess() {
		if (mnFileProcess == null) {
			mnFileProcess = new JMenu("Data Process");
			mnFileProcess.add(getMntmInput());
			mnFileProcess.add(getMntmUpdate());
			mnFileProcess.add(getMntmList());
		}
		return mnFileProcess;
	}
	private JMenuItem getMntmInput() {
		if (mntmInput == null) {
			mntmInput = new JMenuItem("Input");
			mntmInput.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {		
					if(input == null){
						input = new MapInput(hm);                       // hm을 갖고 Internal Frame을 생성하게 됨.
						input.setBounds(0,0,386,151);
					}
					contentPane.add(input);
					input.setVisible(true);
					
					
					
				}
			});
		}
		return mntmInput;
	}
	private JMenuItem getMntmUpdate() {
		if (mntmUpdate == null) {
			mntmUpdate = new JMenuItem("Update");
			mntmUpdate.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(update == null){
						update = new MapUpdate(hm); 
						update.setBounds(0,151,386,175);
					}
					contentPane.add(update);
					update.setVisible(true);
				}
			});
		}
		return mntmUpdate;
	}
	private JMenuItem getMntmList() {
		if (mntmList == null) {
			mntmList = new JMenuItem("List");
			mntmList.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if(list == null){
						list = new MapList(hm);
						list.setBounds(386,0,720,442);
					}
					contentPane.add(list);
					list.setVisible(true);
				}
			});
		}
		return mntmList;
	}
	private JMenu getMnFile() {
		if (mnFile == null) {
			mnFile = new JMenu("File");
			mnFile.add(getMntmNewFile());
			mnFile.add(getMntmLoad());
			mnFile.add(getMntmSave());
			mnFile.add(getMntmSaveAs());
		}
		return mnFile;
	}
	private JMenuItem getMntmNewFile() {
		if (mntmNewFile == null) {
			mntmNewFile = new JMenuItem("New File");
			mntmNewFile.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						newFile();
					}catch(Exception ex){
						status.toString();
					}
				}
			});
		}
		return mntmNewFile;
	}
	private JMenuItem getMntmLoad() {
		if (mntmLoad == null) {
			mntmLoad = new JMenuItem("Load");
			mntmLoad.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						load();
					}catch(Exception ex){
						status.toString();
					}
				}
			});
		}
		return mntmLoad;
	}
	private JMenuItem getMntmSave() {
		if (mntmSave == null) {
			mntmSave = new JMenuItem("Save");
			mntmSave.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						save();
					}catch(Exception ex){
						status.toString();
					}
				}
			});
		}
		return mntmSave;
	}
	private JMenuItem getMntmSaveAs() {
		if (mntmSaveAs == null) {
			mntmSaveAs = new JMenuItem("Save As");
			mntmSaveAs.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						saveAs();
					}catch(Exception ex){
						status.toString();
					}
				}
			});
		}
		return mntmSaveAs;
	}
	private JLabel getStatus() {
		if (status == null) {
			status = new JLabel("New label");
			status.setBounds(12, 488, 900, 15);
		}
		return status;
	}
}
